<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar style="background-color: #F3F3F3;" fixed>
      <template v-if="flag===2" #title>
        <span style="font-size: 18px; color: #FF8800" @click="onShowArticleType" >{{navTitle}}</span>
        <van-icon name="arrow-down" color="#FF8800" @click="onShowArticleType" ></van-icon>
      </template>
      <template v-else="" #title>
        <span style="font-size: 18px; color: #FF8800">{{navTitle}}</span>
      </template>
      <template #left>
        <span style="font-size: 16px" @click="onBack">取消</span>
      </template>
      <template #right>
        <span style="font-size: 16px" @click="onPublish">发布</span>
      </template>
      <van-icon name="star-o" size="20px" color="gray" style="font-weight: bold"/>
    </van-nav-bar>
    <!-- 编辑区域 -->
    <div style="padding-top: 50px">
      <!-- 标题 -->
      <van-cell-group v-show="showTitle">
        <van-field v-model="title" size="large" style="font-size: 18px;font-weight: bold" placeholder="标题" />
      </van-cell-group>
      <!-- 内容段落 -->
      <div style="text-align: left" v-for="(s,idx) in sectionList" :key="idx">
        <van-field
          type="textarea"
          v-model="s.content"
          :border="false"
          :autosize=" { maxHeight: 500, minHeight: 50 }"
          maxlength="200"
          size="large"
          style="font-size: 16px"
          :placeholder="'段落' + (idx+1)"
        >
          <van-icon @click="onDelSection(idx)" v-show="showCloseSec(s,idx)" slot="right-icon" name="cross" size="25" style="margin-top: -25px"></van-icon>
        </van-field>
        <!-- 上传区域 -->
        <van-uploader v-model="s.fileList" @click-preview="onImgPreview" multiple style="padding-left: 10px" preview-size="60px" accept="image/*"/>
        <van-divider style="padding-left: 10px"/>
      </div>
      <!-- 视频预览 -->
      <van-overlay :show="videoShow" @click="videoShow = false" z-index="999" style="background-color: black;display: flex; align-items: center; justify-content: center">
        <div @click.stop>
          <video :src="videoSrc" autoplay loop></video>
        </div>
      </van-overlay>

      <!-- footbar -->
      <div class="wrapper">
        <div class="wrapper-flex" @click="onAddSection">
          <van-icon name="add-o" size="25"/>
          <span>添加段落</span>
        </div>
      </div>
    </div>
    <!-- 文章类型选择 -->
    <ArticleType :types="articleTypes" :isShow="articleTypeShow" :onChange="onShowChange" :onChose="onChoseArticleType"></ArticleType>
  </div>
</template>

<script>
import lrz from 'lrz'
import ArticleType from '@/components/ArticleType.vue'
export default {
  name: 'Edit',
  components: {
    ArticleType: ArticleType
  },
  data () {
    return {
      navTitle: '', // 导航栏标题
      flag: 0, // 编辑标志(0评论文章 1回复评论 2写文章)
      articleType: 0, // 文章类型(flag=2有效)
      title: '', // 文章标题
      fileList: [], // 文件列表
      images: '', // 文章图片列表
      sectionList: [
        { content: '', fileList: [] }
      ],
      // 上传凭证
      uploadTokenList: [],
      // 视频预览
      videoSrc: null,
      videoShow: false,
      // 文章类型选择
      articleTypeShow: false,
      // 文章类型列表
      articleTypes: [
        { id: 1, text: '国内新闻', icon: require('@/assets/icon/news-china.png') },
        { id: 2, text: '老挝新闻', icon: require('@/assets/icon/news-lao.png') },
        { id: 3, text: '老漂故事', icon: require('@/assets/icon/rover.png') },
        { id: 4, text: '爆料吐槽', icon: require('@/assets/icon/disclose.png') },
        { id: 5, text: '同胞互助', icon: require('@/assets/icon/help.png') },
        { id: 99, text: '战疫情', icon: require('@/assets/icon/epidemic.png') }
      ]
    }
  },
  computed: {
    showTitle: function () {
      if (this.flag === 2) {
        return true
      } else {
        return false
      }
    },
    uploadType: function () {
      switch (this.flag) {
        case 0:
          return 2 // 评论
        case 1:
          return 2 // 评论
        case 2:
          return 1 // 文章
        default:
          return 1 // 文章
      }
    }
  },
  mounted () {
    this.flag = parseInt(this.$route.query.flag)
    this.articleType = parseInt(this.$route.query.type)
    this.navTitle = this.$route.query.title
  },
  activated () {
    this.flag = parseInt(this.$route.query.flag)
    this.articleType = parseInt(this.$route.query.type)
    this.navTitle = this.$route.query.title
  },
  methods: {
    // 段落删除按钮是否显示
    showCloseSec (s, idx) {
      return s.content === '' && s.fileList.length <= 0 && (idx !== 0 || (idx === 0 && this.sectionList.length > 1))
    },
    // 返回
    onBack () {
      let rst = this.checkEmpty()
      if (!rst.isEmpty) {
        console.log('fuck!!!!!!!')
        this.$dialog.confirm({
          title: '确定放弃编辑吗?',
          message: '放弃后已编辑内容将丢失！'
        })
          .then(() => {
            this.title = ''
            this.sectionList = [{ content: '', fileList: [] }]
            this.images = []
            this.$router.back()
          })
          .catch(() => {
            // on cancel
          })
      } else {
        this.title = ''
        this.sectionList = [{ content: '', fileList: [] }]
        this.images = ''
        this.$router.back()
      }
    },
    // 判断是否内容为空
    checkEmpty () {
      let isEmpty = true
      let fileList = []
      if (this.title !== '') {
        isEmpty = false
      }
      this.sectionList.forEach((s) => {
        if (s.content !== '') {
          isEmpty = false
        }
        s.fileList.forEach((f) => {
          fileList.push(f.file.name)
          isEmpty = false
        })
      })
      return { isEmpty: isEmpty, fileList: fileList }
    },
    // 发布
    onPublish () {
      let rst = this.checkEmpty()
      if (rst.isEmpty) {
        return
      }
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true,
        loadingType: 'spinner',
        overlay: true
      })
      this.images = ''
      // 获取uploadtoken
      this.$api.getUploadTokenReq({ type: this.uploadType, fileList: rst.fileList })
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            this.uploadTokenList = resp.tokenList
            // 上传
            this.uploadFile(0, 0, 0)
          }
        })
        .catch((err) => {
          console.log('上传凭证获取失败', err)
          this.$toast('上传凭证获取失败')
        })
    },
    // 上传文件
    uploadFile (secIdx, fIdx, idx) {
      for (;secIdx <= this.sectionList.length - 1;) {
        if (fIdx > this.sectionList[secIdx].fileList.length - 1) {
          secIdx = secIdx + 1
          fIdx = 0
        } else {
          break
        }
      }
      if ((secIdx > this.sectionList.length - 1) || (fIdx > this.sectionList[secIdx].fileList.length - 1)) {
        this.uploadOver()
        return
      }
      // const { uptoken } = this.state
      // const uptoken = 'oC2bsLwQ6Rr9WenMzz3R4vYlyY3TlpUcwP8p8-tC:IUmajyuJzNSf6I5nDlWoEfpyWY8=:eyJzY29wZSI6Imxhby1hcHAiLCJkZWFkbGluZSI6MTU4ODI1ODg1NH0='
      // const file = this.dataURLToBlob(this.sectionList[secIdx].fileList[fIdx].content) // Blob 对象，上传的文件
      // this.$util.compressImage(this.sectionList[secIdx].fileList[fIdx].content) // Blob 对象，上传的文件
      lrz(this.sectionList[secIdx].fileList[fIdx].content)
        .then((rst) => {
          console.log('idx--------------========', idx)
          console.log('lrz--------------========', rst, this.uploadTokenList[idx].newName)
          const file = rst.file
          const key = this.uploadTokenList[idx].newName // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
          let config = {
            useCdnDomain: true, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
            region: null// this.$qiniu.region.z0 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
          }
          let putExtra = {
            // fname: this.sectionList[secIdx].fileList[fIdx].file.name, // 文件原文件名
            fname: null, // this.uploadTokenList[idx].newName, // 文件名
            params: { a: 111, b: 222 }, // 用来放置自定义变量
            mimeType: null // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
          }
          let observable = this.$qiniu.upload(file, key, this.uploadTokenList[idx].token, putExtra, config)
          observable.subscribe({
            next: (res) => {
              // 主要用来展示进度
              let total = res.total
              console.log('进度：' + parseInt(total.percent) + '%', secIdx, fIdx)
            },
            error: (err) => {
              // 失败报错信息
              console.log('上传失败', secIdx, fIdx, err)
            },
            complete: (res) => {
              // 接收成功后返回的信息
              console.log('上传成功', secIdx, fIdx, res)
              this.sectionList[secIdx].fileList[fIdx].file.newName = res.key
              let nextSId = secIdx
              let nextFId = fIdx
              if (nextFId >= this.sectionList[nextSId].fileList.length - 1) {
                nextSId = secIdx + 1
                nextFId = 0
              } else {
                nextFId = fIdx + 1
              }
              idx = idx + 1
              console.log('=========', nextSId, nextFId)
              this.uploadFile(nextSId, nextFId, idx)
            }
          })
        })
        .catch((err) => {
          this.$toast('压缩失败', err)
          console.log('压缩失败', err)
        })
      // console.log(file)
    },
    // 上传完毕
    uploadOver () {
      let finalContent = ''
      let pFormat = '<p style="text-align: left;">{0}</p>'
      let imgFormat = '<img class="content-img" src="{0}"/>'
      // let imgFormat = '<van-image fit="cover" src="{0}" style="width: 30%;height: 50px;"/>'
      // imgFormat = '<div><img src="{0}" class="van-image__img" style="object-fit: cover;"></div>'
      this.sectionList.forEach((s) => {
        finalContent = finalContent + String.format(pFormat, s.content.replace(/[\n\r]/g, '<br>'))
        finalContent = '<div>' + finalContent
        s.fileList.forEach((f) => {
          console.log(f)
          finalContent = finalContent + String.format(imgFormat, 'http://laoapp.antegg.net/' + f.file.newName)
          this.images = this.images + 'http://laoapp.antegg.net/' + f.file.newName + ','
        })
        finalContent = finalContent + '</div>'
      })
      this.images = this.images.substring(0, this.images.lastIndexOf(','))
      console.log('------finalContent----' + finalContent)
      switch (parseInt(this.$route.query.flag)) {
        case 0:
          this.onComment(finalContent)
          break
        case 1:
          this.onComment(finalContent)
          break
        case 2: // 写文章
          this.onWrite(finalContent, parseInt(this.articleType))
          break
        default:
          break
      }
    },
    // 添加段落
    onAddSection () {
      if (this.sectionList.length >= 30) {
        this.$toast('太多我会承受不起')
        return
      }
      this.sectionList.push({ content: '', fileList: [] })
    },
    // 删除段落
    onDelSection (idx) {
      this.sectionList.splice(idx, 1)
    },
    // 评论
    onComment (finalContent) {
      this.$api.commentReq({ type: parseInt(this.$route.query.flag), id: parseInt(this.$route.query.id), content: finalContent })
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            this.title = ''
            this.sectionList = [{ content: '', fileList: [] }]
            this.$toast.success('发布成功')
            setTimeout(() => {
              this.$toast.clear()
              this.onBack()
            }, 1000)
          }
        })
        .catch(() => {
          this.$toast.fail('发布失败')
        })
    },
    // 写文章
    onWrite (finalContent, type) {
      this.$api.writeArticleReq({ type: type, title: this.title, images: this.images, content: finalContent })
        .then((resp) => {
          if (resp.errMsg === 'OK') {
            this.title = ''
            this.sectionList = [{ content: '', fileList: [] }]
            this.images = ''
            this.$toast.success('发布成功\n审核后可见')
            setTimeout(() => {
              this.$toast.clear()
              this.onBack()
            }, 2000)
          }
        })
        .catch(() => {
          this.$toast.fail('发布失败')
        })
    },
    // 图片预览
    onImgPreview (file, detail) {
      console.log('file---------', file)
      console.log('detail---------', detail)
      // if (/video\/\w+/.test(file.file.type)) {
      // this.playerOptions.sources[0].type = file.type
      this.videoShow = true
      this.videoSrc = file.content
      // this.playerOptions.sources[0].src = URL.createObjectURL(file.content)
      console.log('视频文件！', file.file.type)
      // }
    },
    // 文章类型选择
    onChoseArticleType (idx) {
      console.log('onChoseType', idx, this.articleTypes[idx].text)
      this.navTitle = this.articleTypes[idx].text
      this.articleTypeShow = false
    },
    // 显示文章类型
    onShowArticleType () {
      this.articleTypeShow = true
    },
    // 文章类型显示/关闭状态切换
    onShowChange (val) {
      this.articleTypeShow = val
    }
  }
}
</script>

<style scoped>
  .wrapper{
    padding: 10px 0;
    position: fixed;
    bottom: 0px;
    width: 100%;
    z-index: 101;
    border-top: #F0F0F0 1px solid;
    /*padding-bottom: 20px;*/
  }
  .wrapper-flex{
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
</style>
